package com.chen.glide_ex;


import android.support.annotation.WorkerThread;
import android.widget.ImageView;

import java.io.IOException;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

/**
 * Created by chenjian on 2019/3/5 17:26.
 * sun.misc.BASE64Decoder;
 * sun.misc.BASE64Encoder;
 */
public final class Base64tUtil {
    private Base64tUtil() {
        throw new RuntimeException("....failed...");
    }
    /**
     * @param filePath
     * @return
     */
   /* @WorkerThread
    public static String encodeBase64(String filePath) {

        BASE64Encoder base64Encoder = new BASE64Encoder();
        return base64Encoder.encode(StorageUtil.readBytes(filePath));
    }*/

    /**
     * @param bytes 例如  一帧图像  byte[]->转成 base64
     * @return
     */
    @WorkerThread
    public static String encodeBase64(byte[] bytes) {

        BASE64Encoder base64Encoder = new BASE64Encoder();
        return base64Encoder.encode(bytes);
    }

    @WorkerThread
    public static byte[] decodeBase64(String base64) {

        BASE64Decoder decoder = new BASE64Decoder();
        try {
            return decoder.decodeBuffer(base64);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new byte[]{};

    }

    /**
     * 不直接加载 String 类型的base64的目的: 会与 系统的
     * com.bumptech.glide.load.model.DataUrlLoader.StreamFactory 冲突,导致加载失败
     * ,所以 重新建了一个Base64Entity 实体
     * 加载base64图片
     */
    public static void LoadImageFromBase64(ImageView imageView, String base64) {
        Base64Entity entity = new Base64Entity();
        entity.setBase64(base64);
        GlideApp.with(imageView).load(entity).into(imageView);
    }


}
